#include "VideoMonitorWindow.h"
#include "CryptString.h"
#include <QElapsedTimer>
// 初始化静态用户数据库（程序启动时为空，注册后添加数据）
QMap<QString, QString> VideoMonitorWindow::m_userDB;

VideoMonitorWindow::VideoMonitorWindow(QWidget *parent)
    : QMainWindow(parent), m_tcpClient(nullptr), m_stackedWidget(nullptr), m_loginWidget(nullptr)
    , m_registerWidget(nullptr), m_monitorContainer(nullptr), m_ffmpeg1(nullptr), m_ffmpeg2(nullptr)
    , m_ffmpeg3(nullptr), m_ffmpeg4(nullptr),m_videoLabel1(nullptr), m_videoLabel2(nullptr)
    , m_networkManager(nullptr), m_ptzStopTimer(nullptr) , m_ptzDuration(500)
    , m_ptzDurationLabel(nullptr), m_ptzDurationSlider(nullptr), m_currentChannel(1)
{
    // 保持原窗口样式：无边框+最小化/最大化按钮
    setWindowFlags(Qt::FramelessWindowHint | Qt::WindowMinMaxButtonsHint);
    // 初始化TCP客户端并连接信号槽
    m_tcpClient = new tcpclient(this);
    connect(m_tcpClient, &tcpclient::registerStep1Result,
            this, &VideoMonitorWindow::onRegisterStep1Result);
    connect(m_tcpClient, &tcpclient::registerStep2Result,
            this, &VideoMonitorWindow::onRegisterStep2Result);
    connect(m_tcpClient, &tcpclient::loginStep1Result,
            this, &VideoMonitorWindow::onLoginStep1Result);
    connect(m_tcpClient, &tcpclient::loginStep2Result,
            this, &VideoMonitorWindow::onLoginStep2Result);
    connect(m_tcpClient, &tcpclient::streamUrlReceived,
            this, &VideoMonitorWindow::onStreamUrlReceived);
    connect(m_tcpClient, &tcpclient::ptzControlResult,
            this, &VideoMonitorWindow::onPTZControlResult);
    connect(m_tcpClient, &tcpclient::metadataReceived,
            this, &VideoMonitorWindow::onMetadataReceived);
    connect(m_tcpClient, &tcpclient::videoFrameReceived,
            this, &VideoMonitorWindow::onVideoFrameReceived);
    connect(m_tcpClient, &tcpclient::connectError,this, [=](const QString &msg) {
        QMessageBox::critical(this, "网络错误", "连接服务器失败：" + msg);
    });

    // 添加云台控制定时器初始化
    m_ptzTimer = new QTimer(this);
    m_ptzTimer->setSingleShot(true); // 单次触发
    connect(m_ptzTimer, &QTimer::timeout, this, &VideoMonitorWindow::stopPTZMovement);

    initUI();
    initVideoPlayers();
}

VideoMonitorWindow::~VideoMonitorWindow()
{
    qDebug() << "开始销毁VideoMonitorWindow";

    // 停止所有视频播放
    QVector<FFmpegKits*> players = {m_ffmpeg1, m_ffmpeg2, m_ffmpeg3, m_ffmpeg4,
                                    m_ffmpeg5, m_ffmpeg6, m_ffmpeg7, m_ffmpeg8};

    for (auto player : players) {
        if (player) {
            qDebug() << "停止播放器";
            player->cleanup();
        }
    }

    // 删除所有播放器对象
    qDebug() << "删除播放器对象";
    delete m_ffmpeg1;
    delete m_ffmpeg2;
    delete m_ffmpeg3;
    delete m_ffmpeg4;
    delete m_ffmpeg5;
    delete m_ffmpeg6;
    delete m_ffmpeg7;
    delete m_ffmpeg8;

    // 删除其他指针成员
    qDebug() << "删除其他对象";
    delete m_tcpClient;
    delete m_ptzStopTimer;
    delete m_networkManager;

    qDebug() << "VideoMonitorWindow销毁完成";
}

void VideoMonitorWindow::initUI()
{
    setWindowTitle("视频监控管理平台");
    setMinimumSize(950, 800);

    // 1. 创建堆叠窗口
    m_stackedWidget = new QStackedWidget(this);

    // 2. 初始化登录和注册界面
    m_loginWidget = new Login(this);
    m_registerWidget = new Register(this);

    // 3. 初始化监控界面
    initMonitorInterface();  // 初始化监控界面组件

    // 4. 添加所有界面到堆叠窗口（索引：0=登录，1=注册，2=监控）
    m_stackedWidget->addWidget(m_loginWidget);
    m_stackedWidget->addWidget(m_registerWidget);
    m_stackedWidget->addWidget(m_monitorContainer);

    // 5. 连接信号与槽
    connect(m_loginWidget, &Login::loginRequested, this, &VideoMonitorWindow::handleLoginRequest);
    connect(m_loginWidget, &Login::switchToRegister, this, &VideoMonitorWindow::switchToRegisterInterface);
    connect(m_registerWidget, &Register::registerRequested, this, &VideoMonitorWindow::handleRegisterRequest);
    connect(m_registerWidget, &Register::switchToLogin, this, &VideoMonitorWindow::switchToLoginInterface);
    connect(m_deviceTree, &QTreeWidget::itemDoubleClicked, this, &VideoMonitorWindow::onDeviceItemDoubleClicked);

    // 新增：连接注册成功信号到登录页面的用户名设置
    connect(m_registerWidget, &Register::registerSuccess,
            m_loginWidget, &Login::setUsername);

    // 6. 设置中心部件
    setCentralWidget(m_stackedWidget);
    m_stackedWidget->setCurrentIndex(0);  // 初始显示登录界面
}



// ==================== 监控主界面初始化（保留原功能，修正细节） ====================
void VideoMonitorWindow::initMonitorInterface()
{
    // 监控界面总容器
    m_monitorContainer = new QWidget(this);
    QVBoxLayout *mainLayout = new QVBoxLayout(m_monitorContainer);
    mainLayout->setSpacing(0);
    mainLayout->setContentsMargins(0, 0, 0, 0);

    // =========== 顶部工具栏 ==========
    m_topWidget = new QWidget(m_monitorContainer);
    QHBoxLayout *topLayout = new QHBoxLayout(m_topWidget);

    m_titleLabel = new QLabel("视频监控管理平台\nVideo Surveillance Management Platform", m_topWidget);
    m_titleLabel->setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
    m_titleLabel->setStyleSheet("color:white");

    // 功能按键（修正原拼写错误btnVoideMonitor为btnVideoMonitor）
    m_btnVideoMonitor = new QPushButton("视频监控", m_topWidget);
    m_btnVideoMonitor->setStyleSheet("background-color:skyblue;");
    m_btnVideoPlayback = new QPushButton("视频回放", m_topWidget);
    m_btnVideoPlayback->setStyleSheet("background-color:skyblue;");
    m_btnElectronicMap = new QPushButton("电子地图", m_topWidget);
    m_btnElectronicMap->setStyleSheet("background-color:skyblue;");
    m_btnLogQuery = new QPushButton("日志查询", m_topWidget);
    m_btnLogQuery->setStyleSheet("background-color:skyblue;");
    m_btnSystemSetting = new QPushButton("系统设置", m_topWidget);
    m_btnSystemSetting->setStyleSheet("background-color:skyblue;");

    // 时间显示
    m_timeLabel = new QLabel("00:00:00", m_topWidget);
    m_timeLabel->setAlignment(Qt::AlignRight | Qt::AlignCenter);
    m_timeLabel->setStyleSheet("color:white;font-size:16px;");
    m_timer = new QTimer(this);
    m_timer->setInterval(1000);
    connect(m_timer, &QTimer::timeout, this, &VideoMonitorWindow::updateTime);
    updateTime();
    m_timer->start();

    // 窗口控制按钮（最小化、最大化/还原、关闭）
    QHBoxLayout *windowControlLayout = new QHBoxLayout();
    windowControlLayout->setSpacing(2);
    windowControlLayout->setContentsMargins(0, 0, 0, 0);

    QPushButton *btnMinimize = new QPushButton("−", m_topWidget);
    btnMinimize->setFixedSize(40, 40);
    btnMinimize->setStyleSheet("QPushButton { background: transparent; color: white; border: none; font-size: 50px; }"
                               "QPushButton:hover { background: #5dade2; }");
    connect(btnMinimize, &QPushButton::clicked, this, &QMainWindow::showMinimized);

    QPushButton *btnMaximize = new QPushButton("□", m_topWidget);
    btnMaximize->setFixedSize(40, 40);
    btnMaximize->setStyleSheet("QPushButton { background: transparent; color: white; border: none; font-size: 50px;font-weight: bold;}"
                               "QPushButton:hover { background: #5dade2; }");
    connect(btnMaximize, &QPushButton::clicked, [this, btnMaximize]() {
        if (isMaximized()) {
            showNormal();
            btnMaximize->setText("□");
        } else {
            showMaximized();
            btnMaximize->setText("◫");
        }
    });

    QPushButton *btnClose = new QPushButton("×", m_topWidget);
    btnClose->setFixedSize(40, 40);
    btnClose->setStyleSheet("QPushButton { background: transparent; color: white; border: none; font-size: 50px;}"
                            "QPushButton:hover { background: #e74c3c; }");
    connect(btnClose, &QPushButton::clicked, this, &QMainWindow::close);

    windowControlLayout->addWidget(btnMinimize);
    windowControlLayout->addWidget(btnMaximize);
    windowControlLayout->addWidget(btnClose);

    topLayout->addWidget(m_titleLabel);
    topLayout->addSpacing(20);
    topLayout->addWidget(m_btnVideoMonitor);
    topLayout->addWidget(m_btnLogQuery);
    topLayout->addWidget(m_btnVideoPlayback);
    topLayout->addWidget(m_btnElectronicMap);
    topLayout->addWidget(m_btnSystemSetting);
    topLayout->addStretch();
    topLayout->addWidget(m_timeLabel);
    topLayout->addSpacing(10);
    topLayout->addLayout(windowControlLayout);
    m_topWidget->setStyleSheet("background-color:#2c3e50;padding:10px;");
    topLayout->setContentsMargins(10, 5, 5, 5);

    // =========== 左侧信息栏 ==========
    m_leftWidget = new QWidget(m_monitorContainer);
    m_leftWidget->setMinimumWidth(200);
    m_leftWidget->setStyleSheet("background-color:#ecf0f1;");
    QVBoxLayout *leftLayout = new QVBoxLayout(m_leftWidget);

    m_leftTabWidget = new QTabWidget(m_leftWidget);
    m_windowInfoWidget = new QWidget(m_leftTabWidget);
    QVBoxLayout *windowLayout = new QVBoxLayout(m_windowInfoWidget);

    QLabel *logLabel = new QLabel("云台控制日志");
    logLabel->setStyleSheet("font-weight:bold;padding:5px;");
    m_logTextEdit = new QTextEdit(m_windowInfoWidget);
    m_logTextEdit->setReadOnly(true);
    m_logTextEdit->setMaximumHeight(800);

    windowLayout->addWidget(logLabel);
    windowLayout->addWidget(m_logTextEdit);

    m_leftTabWidget->addTab(m_windowInfoWidget, "窗口信息");
    leftLayout->addWidget(m_leftTabWidget);

    // =========== 中间通道布局 ==========
    m_centralWidget = new QWidget(m_monitorContainer);
    QVBoxLayout *centralLayout = new QVBoxLayout(m_centralWidget);
    m_channelLayout = new QGridLayout();
    m_channelLayout->setSpacing(10);
    m_channelLayout->setContentsMargins(5, 5, 5, 5); // 添加边距

    // 通道创建工具函数（简化重复代码）
    auto createChannel = [this](QWidget *&channel, QLabel *&label, const QString &name)
    {
        channel = new QWidget();
        channel->setStyleSheet("border:1px solid #34495e;background-color:#2c3e50");
        channel->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); // 设置大小策略
        QVBoxLayout *chLayout = new QVBoxLayout(channel);
        chLayout->setContentsMargins(2, 2, 2, 2);
        chLayout->setSpacing(2);

        label = new QLabel(name);
        label->setStyleSheet("color:white;padding:2px;font-size:12px;"); // 减小字体和内边距
        label->setFixedHeight(20); // 固定高度，减少占用空间
        label->setAlignment(Qt::AlignCenter);

        QLabel *placeholder = new QLabel("实时视频流");
        placeholder->setAlignment(Qt::AlignCenter);
        placeholder->setStyleSheet("color:#bdc3c7;font-size:12px;");
        placeholder->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

        chLayout->addWidget(label);
        chLayout->addWidget(placeholder);

        channel->setMinimumSize(400, 200);
    };

    createChannel(m_channel1, m_channel1Label, "通道1");
    createChannel(m_channel2, m_channel2Label, "通道2");
    createChannel(m_channel3, m_channel3Label, "通道3");
    createChannel(m_channel4, m_channel4Label, "通道4");

    m_channelLayout->addWidget(m_channel1, 0, 0);
    m_channelLayout->addWidget(m_channel2, 0, 1);
    m_channelLayout->addWidget(m_channel3, 1, 0);
    m_channelLayout->addWidget(m_channel4, 1, 1);

    // 关键：设置行和列的拉伸因子，确保均匀分配空间
    m_channelLayout->setRowStretch(0, 1); // 第一行拉伸因子为1
    m_channelLayout->setRowStretch(1, 1); // 第二行拉伸因子为1
    m_channelLayout->setColumnStretch(0, 1); // 第一列拉伸因子为1
    m_channelLayout->setColumnStretch(1, 1); // 第二列拉伸因子为1

    centralLayout->addLayout(m_channelLayout);

    // =========== 右侧控制区 ==========
    m_rightWidget = new QWidget(m_monitorContainer);
    m_rightWidget->setMinimumWidth(200);
    m_rightWidget->setStyleSheet("background-color:#ecf0f1");
    QVBoxLayout *rightLayout = new QVBoxLayout(m_rightWidget);

    // 设备列表
    m_deviceListWidget = new QWidget(m_rightWidget);
    QVBoxLayout *deviceLayout = new QVBoxLayout(m_deviceListWidget);
    QLabel *deviceTitle = new QLabel("设备列表");
    deviceTitle->setStyleSheet("font-weight:bold;padding:5px;");
    m_deviceTree = new QTreeWidget(m_deviceListWidget);
    m_deviceTree->setHeaderLabel("监控设备");
    QTreeWidgetItem *rootItem1 = new QTreeWidgetItem(QStringList() << "网络视频1");
    rootItem1->addChildren({new QTreeWidgetItem(QStringList() << "主码流"), new QTreeWidgetItem(QStringList() << "子码流")});
    QTreeWidgetItem *rootItem2 = new QTreeWidgetItem(QStringList() << "网络视频2");
    rootItem2->addChildren({new QTreeWidgetItem(QStringList() << "主码流"), new QTreeWidgetItem(QStringList() << "子码流")});
    QTreeWidgetItem *rootItem3 = new QTreeWidgetItem(QStringList() << "网络视频3");
    rootItem3->addChildren({new QTreeWidgetItem(QStringList() << "主码流"), new QTreeWidgetItem(QStringList() << "子码流")});
    QTreeWidgetItem *rootItem4 = new QTreeWidgetItem(QStringList() << "网络视频4");
    rootItem4->addChildren({new QTreeWidgetItem(QStringList() << "主码流"), new QTreeWidgetItem(QStringList() << "子码流")});
    m_deviceTree->addTopLevelItem(rootItem1);
    m_deviceTree->addTopLevelItem(rootItem2);
    m_deviceTree->addTopLevelItem(rootItem3);
    m_deviceTree->addTopLevelItem(rootItem4);
    deviceLayout->addWidget(deviceTitle);
    deviceLayout->addWidget(m_deviceTree);

    // 云控制
    m_ptzControlWidget = new QWidget(m_rightWidget);
    m_ptzControlWidget->setStyleSheet("padding:10px");
    QVBoxLayout *ptzLayout = new QVBoxLayout(m_ptzControlWidget);
    QLabel *ptzTitle = new QLabel("云控制");
    ptzTitle->setStyleSheet("font-weight:bold;padding:5px;");

    // 方向控制网格
    QGridLayout *dirLayout = new QGridLayout();
    m_btnLon = new QPushButton("↖");
    m_btnUp = new QPushButton("↑");
    m_btnRon = new QPushButton("↗");
    m_btnLeft = new QPushButton("←");
    m_btnCenter = new QPushButton("+");
    m_btnRight = new QPushButton("→");
    m_btnLup = new QPushButton("↙");
    m_btnDown = new QPushButton("↓");
    m_btnRup = new QPushButton("↘");
    dirLayout->addWidget(m_btnLon, 0, 0); dirLayout->addWidget(m_btnUp, 0, 1); dirLayout->addWidget(m_btnRon, 0, 2);
    dirLayout->addWidget(m_btnLeft, 1, 0); dirLayout->addWidget(m_btnCenter, 1, 1); dirLayout->addWidget(m_btnRight, 1, 2);
    dirLayout->addWidget(m_btnLup, 2, 0); dirLayout->addWidget(m_btnDown, 2, 1); dirLayout->addWidget(m_btnRup, 2, 2);

    // 变焦/聚焦/光圈控制
    QHBoxLayout *zoomLayout = new QHBoxLayout();
    m_btnZoomIn = new QPushButton("变焦+");
    m_btnZoomOut = new QPushButton("变焦-");
    zoomLayout->addWidget(m_btnZoomIn);
    zoomLayout->addWidget(m_btnZoomOut);

    QHBoxLayout *focusLayout = new QHBoxLayout();
    m_btnFocusIn = new QPushButton("聚焦+");
    m_btnFocusOut = new QPushButton("聚焦-");
    focusLayout->addWidget(m_btnFocusIn);
    focusLayout->addWidget(m_btnFocusOut);

    QHBoxLayout *irisLayout = new QHBoxLayout();
    m_btnIrisIn = new QPushButton("光圈+");
    m_btnIrisOut = new QPushButton("光圈-");
    irisLayout->addWidget(m_btnIrisIn);
    irisLayout->addWidget(m_btnIrisOut);

    // 在云台控制布局中添加持续时间控制（在ptzLayout->addStretch();之前添加）
    QHBoxLayout *durationLayout = new QHBoxLayout();
    QLabel *durationLabel = new QLabel("点动时间:");
    m_ptzDurationSlider = new QSlider(Qt::Horizontal);
    m_ptzDurationSlider->setRange(100, 3000); // 100ms 到 3000ms
    m_ptzDurationSlider->setValue(m_ptzDuration);
    m_ptzDurationLabel = new QLabel(QString("%1ms").arg(m_ptzDuration));
    // 连接滑块值变化信号
    connect(m_ptzDurationSlider, &QSlider::valueChanged, this, &VideoMonitorWindow::setPTZDuration);

    // 将持续时间控制添加到云台控制布局中
    durationLayout->addWidget(durationLabel);
    durationLayout->addWidget(m_ptzDurationSlider);
    durationLayout->addWidget(m_ptzDurationLabel);


    // 组装云控制区
    ptzLayout->addWidget(ptzTitle);
    ptzLayout->addLayout(dirLayout);
    ptzLayout->addLayout(zoomLayout);
    ptzLayout->addLayout(focusLayout);
    ptzLayout->addLayout(irisLayout);
    ptzLayout->addStretch();
    ptzLayout->addLayout(durationLayout); // 添加到云台控制布局中

    // 组装右侧控制区
    rightLayout->addWidget(m_deviceListWidget);
    rightLayout->addWidget(m_ptzControlWidget);
    rightLayout->setContentsMargins(5, 5, 5, 5);

    // 组装监控界面总布局
    mainLayout->addWidget(m_topWidget);
    QHBoxLayout *contentLayout = new QHBoxLayout();
    contentLayout->addWidget(m_leftWidget);
    contentLayout->addWidget(m_centralWidget, 1); // 中间区域占比1，优先拉伸
    contentLayout->addWidget(m_rightWidget);
    mainLayout->addLayout(contentLayout, 1);

    //云台控制连接
    setupPTZConnections();
}
//登录
void VideoMonitorWindow::onLoginStep1Result(bool success, const QString &msg, const QString &salt)
{
    if (!success) {
        QMessageBox::critical(this, "登录失败", msg);
        return;
    }
    // 第一步成功：用salt加密密码，发送第二步请求
    qDebug() << "登录第一步成功，Salt：" << salt;

    // 直接使用服务器返回的完整盐值，不需要额外解析
    QString fullSalt = salt; // 直接使用完整盐值

    // 加密密码并发送第二步
    QString encryptedPassword = m_tcpClient->generateMd5WithSalt(m_tempLoginPassword, salt);
    m_tcpClient->sendLoginStep2(encryptedPassword);

    // 立即清空临时密码，防止重复使用
    m_tempLoginPassword.clear();
}

void VideoMonitorWindow::onLoginStep2Result(bool success, const QString &msg)
{
    if (success) {
        QMessageBox::information(this, "登录成功", msg);
        // 延迟一下再切换界面，避免资源冲突
        QTimer::singleShot(100, this, [this]() {
            m_stackedWidget->setCurrentIndex(2); // 切换到监控界面
            m_timer->start();

            // 延迟初始化视频播放器
            QTimer::singleShot(500, this, [this]() {
                initVideoPlayers();
            });
        });
    }
    else
    {
        QMessageBox::critical(this, "登录失败", msg);
    }

    // 清空所有临时登录信息
    m_tempLoginUsername.clear();
    m_tempLoginPassword.clear();
}
//处理登录请求
void VideoMonitorWindow::handleLoginRequest(const QString &username, const QString &password)
{
    qDebug() << "发起登录请求-用户名：" << username;

    // 检查TCP连接状态
    if (!m_tcpClient->isConnected()) {
        qDebug() << "当前未连接到服务器，尝试连接...";
        bool connected = m_tcpClient->connectToServer("192.168.96.128", 8000);
        if (!connected) {
            //qDebug() << "连接服务器失败，错误信息:" << m_tcpClient->errorString();
            QMessageBox::critical(this, "连接失败", "无法连接到服务器，请检查网络");
            return;
        } else {
            qDebug() << "成功连接到服务器";
        }
    }

    // 添加连接状态检查
    if (!m_tcpClient->isConnected()) {
        QMessageBox::critical(this, "连接错误", "TCP连接已断开");
        return;
    }
    // 保存临时用户名和密码
    m_tempLoginUsername = username;
    m_tempLoginPassword = password;

    // 发送登录第一步请求（获取Salt）
    m_tcpClient->sendLoginStep1(username);
}

// 处理注册请求
void VideoMonitorWindow::handleRegisterRequest(const QString &username, const QString &password)
{
    qDebug() << "发起注册第一步-用户名：" << username;

    // 检查TCP连接状态
    if (!m_tcpClient->isConnected()) {
        // 尝试连接服务器（实际项目中IP和端口应配置在配置文件中）
        bool connected = m_tcpClient->connectToServer("192.168.96.128", 8000);
        if (!connected) {
            QMessageBox::critical(this, "连接失败", "无法连接到服务器，请检查网络");
            return;
        }
    }

    // 保存临时用户名和密码（用于第二步加密）
    m_tempRegisterUsername = username;
    m_tempRegisterPassword = password;

    // 发送注册第一步请求（获取Salt）
    m_tcpClient->sendRegisterStep1(username);
}

// 处理注册第一步结果（服务器返回Salt或用户名已存在）
void VideoMonitorWindow::onRegisterStep1Result(bool success, const QString &msg, const QString &salt) {
    if (!success) {
        QMessageBox::warning(this, "注册失败", msg);
        return;
    }

    qDebug() << "注册第一步成功，Salt：" << salt;

    // 这里应该直接使用服务器返回的完整盐值，不需要再解析
    // 服务器返回的格式已经是：$1$JpfdiKRW$
    QString fullSalt = salt; // 直接使用完整盐值

    QString encryptedPassword = m_tcpClient->generateMd5WithSalt(m_tempRegisterPassword, fullSalt);
    qDebug() << "加密后的密码：" << encryptedPassword;

    // 发送注册第二步请求
    m_tcpClient->sendRegisterStep2(encryptedPassword);
}

// 处理注册第二步结果（服务器最终确认）
void VideoMonitorWindow::onRegisterStep2Result(bool success, const QString &msg) {
    if (success) {
        QMessageBox::information(this, "注册成功", msg);
        // 注册成功：将用户信息缓存到本地（可选）
        m_userDB.insert(m_tempRegisterUsername, m_tempRegisterPassword);
        // 切换到登录界面并填充用户名
        m_loginWidget->setUsername(m_tempRegisterUsername);
        m_stackedWidget->setCurrentIndex(0);
    } else {
        QMessageBox::warning(this, "注册失败", msg);
    }

    // 清空临时存储
    m_tempRegisterUsername.clear();
    m_tempRegisterPassword.clear();
}

// 切换到登录界面
void VideoMonitorWindow::switchToLoginInterface()
{
    qDebug()<<"切换到登录页面";
    m_stackedWidget->setCurrentIndex(0);
}

// 切换到注册界面
void VideoMonitorWindow::switchToRegisterInterface()
{
    qDebug()<<"切换到注册页面";
    m_stackedWidget->setCurrentIndex(1);
}

void VideoMonitorWindow::updateTime()
{
    QDateTime currentTime = QDateTime::currentDateTime();
    QString timeString = currentTime.toString("HH:mm:ss");
    m_timeLabel->setText(timeString);
}

//初始化视频播放器
void VideoMonitorWindow::initVideoPlayers()
{
    qDebug() << "开始初始化视频播放器...";

    // 停止并删除所有现有的播放器
    QVector<FFmpegKits*> players = {m_ffmpeg1, m_ffmpeg2, m_ffmpeg3, m_ffmpeg4,
                                    m_ffmpeg5, m_ffmpeg6, m_ffmpeg7, m_ffmpeg8};

    for (auto& player : players) {
        if (player) {
            // 先断开所有信号连接
            player->disconnect();
            // 清理资源
            player->cleanup();
            // 删除对象
            delete player;
            player = nullptr;
        }
    }

    qDebug() << "创建新的视频播放器实例...";
    // 只为实际使用的通道创建播放器
    m_ffmpeg1 = new FFmpegKits(this);
    m_ffmpeg2 = new FFmpegKits(this); // 通道1子码流
    m_ffmpeg3 = new FFmpegKits(this);
    m_ffmpeg4 = new FFmpegKits(this); // 通道2子码流

    // 不需要为未使用的通道创建实例
    m_ffmpeg5 = nullptr;
    m_ffmpeg6 = nullptr;
    m_ffmpeg7 = nullptr;
    m_ffmpeg8 = nullptr;

    qDebug() << "获取视频标签...";

    // 获取视频显示标签
    auto getVideoLabel = [](QWidget* channel) -> QLabel* {
        if (channel && channel->layout() && channel->layout()->count() > 1) {
            QLabel* label = qobject_cast<QLabel*>(channel->layout()->itemAt(1)->widget());
            if (label) label->setScaledContents(true);
            return label;
        }
        return nullptr;
    };

    m_videoLabel1 = getVideoLabel(m_channel1);
    m_videoLabel2 = getVideoLabel(m_channel2);
    m_videoLabel3 = getVideoLabel(m_channel3);
    m_videoLabel4 = getVideoLabel(m_channel4);

    // 连接视频帧信号
    connect(m_ffmpeg1, &FFmpegKits::sigGetOneFrame, this, [=](const QImage &image) {
        qDebug() << "接收到通道1主码流的图像，大小:" << image.size();
        if (m_videoLabel1) {
            m_videoLabel1->setPixmap(QPixmap::fromImage(image));
            qDebug() << "已更新通道1显示";
        } else {
            qWarning() << "m_videoLabel1为空";
        }
    }, Qt::UniqueConnection);

    connect(m_ffmpeg2, &FFmpegKits::sigGetOneFrame, this, [=](const QImage &image) {
        if (m_videoLabel1) m_videoLabel1->setPixmap(QPixmap::fromImage(image));
    }, Qt::UniqueConnection);

    connect(m_ffmpeg3, &FFmpegKits::sigGetOneFrame, this, [=](const QImage &image) {
        if (m_videoLabel2) m_videoLabel2->setPixmap(QPixmap::fromImage(image));
    }, Qt::UniqueConnection);

    connect(m_ffmpeg4, &FFmpegKits::sigGetOneFrame, this, [=](const QImage &image) {
        if (m_videoLabel2) m_videoLabel2->setPixmap(QPixmap::fromImage(image));
    }, Qt::UniqueConnection);

    // 添加播放错误处理
    auto addErrorHandler = [this](FFmpegKits* player, const QString& channelName) {
        connect(player, &FFmpegKits::sigPlayError, this, [=](const QString &error) {
            QMessageBox::warning(this, "播放错误", QString("%1播放失败: %2").arg(channelName).arg(error));
        });
    };

    addErrorHandler(m_ffmpeg1, "通道1主码流");
    addErrorHandler(m_ffmpeg2, "通道1子码流");
    addErrorHandler(m_ffmpeg3, "通道2主码流");
    addErrorHandler(m_ffmpeg4, "通道2子码流");

    qDebug() << "视频播放器初始化完成";
}
// 处理接收到的视频流URL
void VideoMonitorWindow::onStreamUrlReceived(int cameraId, bool isMainStream, const QString &url) {
    if (url.isEmpty()) {
        // 服务器采用推送模式，URL为空是正常的
        addLogMessage(QString("开始接收摄像头%1的%2流（推送模式）").arg(cameraId).arg(isMainStream ? "主码" : "子码"));
    } else {
        addLogMessage(QString("获取到摄像头%1的%2流URL: %3").arg(cameraId).arg(isMainStream ? "主码" : "子码").arg(url));
    }
}

// 处理接收到的元数据
void VideoMonitorWindow::onMetadataReceived(const VideoMetadata& metadata) {
    qDebug() << "接收到元数据，摄像头ID:" << metadata.cameraId;
    
    // 检查元数据有效性
    if (metadata.width <= 0 || metadata.height <= 0) {
        qWarning() << "警告：接收到无效的视频元数据 - 分辨率错误" << metadata.width << "x" << metadata.height;
        return;
    }
    
    if (metadata.spsPps.isEmpty()) {
        qWarning() << "警告：接收到的元数据中SPS/PPS数据为空";
        // 即使SPS/PPS为空，也继续尝试初始化，因为某些情况下可能不需要
    }
    
    FFmpegKits* targetPlayer = getPlayerByCameraId(metadata.cameraId);
    if (targetPlayer) {
        targetPlayer->onMetadataReceived(metadata);
    } else {
        qWarning() << "没有找到对应摄像头ID的播放器:" << metadata.cameraId;
    }
}

FFmpegKits* VideoMonitorWindow::getPlayerByCameraId(int cameraId) {
    // 如果摄像头ID为0，默认使用第一个播放器
    if (cameraId == 0) {
        qWarning() << "摄像头ID为0，使用默认播放器(通道1)";
        return m_ffmpeg1;
    }

    // 确保cameraId在有效范围内
    if (cameraId < 1 || cameraId > 4) {
        qWarning() << "无效的摄像头ID:" << cameraId;
        return nullptr;
    }

    // 映射关系：摄像头1 -> 通道1 -> m_ffmpeg1
    switch (cameraId) {
    case 1: return m_ffmpeg1;
    case 2: return m_ffmpeg2;
    case 3: return m_ffmpeg3;
    case 4: return m_ffmpeg4;
    default: return nullptr;
    }
}

// 处理接收到的视频帧
void VideoMonitorWindow::onVideoFrameReceived(const VideoFrame& frame) {
    qDebug() << "收到视频帧 - 摄像头ID:" << frame.cameraId << "，大小:" << frame.size << "，PTS:" << frame.pts;
    
    // 根据摄像头ID分发到不同的播放器
    FFmpegKits* targetPlayer = getPlayerByCameraId(frame.cameraId);
    if (targetPlayer) {
        qDebug() << "将视频帧发送到播放器";
        targetPlayer->onVideoFrameReceived(frame);
    } else {
        qWarning() << "没有找到对应摄像头ID的播放器:" << frame.cameraId;
    }
}


// 添加设备列表项双击处理函数进行子码流与主码流的切换
void VideoMonitorWindow::onDeviceItemDoubleClicked(QTreeWidgetItem *item, int column)
{
    // 忽略父节点，只处理子节点（主码流/子码流）
    if (!item->parent()) return;

    QString deviceName = item->parent()->text(0);
    QString streamType = item->text(0);
    bool isMainStream = (item->text(0) == "主码流");

    int channel = -1;

    // 根据设备名称映射到对应的通道
    if (deviceName == "网络视频1") {
        channel = 1;
    } else if (deviceName == "网络视频2") {
        channel = 2;
    } else if (deviceName == "网络视频3") {
        channel = 3;
        // 通道3和4暂时不支持播放
        QMessageBox::information(this, "提示", "通道3和4暂未配置视频源");
        return;
    } else if (deviceName == "网络视频4") {
        channel = 4;
        QMessageBox::information(this, "提示", "通道3和4暂未配置视频源");
        return;
    }

    if (channel != -1)
    {
        // 通过TCP客户端向服务器请求视频流
        m_tcpClient->sendStreamRequest(channel, isMainStream);
        addLogMessage(QString("请求摄像头%1的%2流").arg(channel).arg(isMainStream ? "主码" : "子码"));
    }
}
//启动视频播放
//void VideoMonitorWindow::startVideoPlayback(int channel, bool isMainStream)
//{
//    try {
//        QString rtspUrl;
//        QString cameraIP;

//        // 根据通道选择摄像头IP
//        if (channel == 1) {cameraIP = m_cameraIp1;}
//        else if (channel == 2) {cameraIP = m_cameraIp2;}
//        // 通道3和4不播放视频
//        else {return;}
//        // 构建RTSP URL
//        rtspUrl = QString("rtsp://admin:admin@%1/live/chn=%2")
//                .arg(cameraIP).arg(isMainStream ? 0 : 1);
//        qDebug() << "准备播放" << rtspUrl;

//        // 为每个通道设置独立的RTSP地址
//        switch(channel) {
//        case 1:
//            if (isMainStream) {
//                // 切换到主码流
//                qDebug() << "切换到通道1主码流";
//                // 1. 停止子码流
//                if (m_ffmpeg2 && m_ffmpeg2->isPlaying()) {
//                    qDebug() << "停止通道1子码流播放器";
//                    m_ffmpeg2->stopPlay();
//                    // 等待线程完全停止
//                    QElapsedTimer timer;
//                    timer.start();
//                    while (m_ffmpeg2->isRunning() && timer.elapsed() < 5000) {
//                        QThread::msleep(10);
//                    }
//                    qDebug() << "通道1子码流播放器已停止";
//                }
//                // 2.主码流播放器
//                if (!m_ffmpeg1) {
//                    m_ffmpeg1 = new FFmpegKits(this);
//                    connect(m_ffmpeg1, &FFmpegKits::sigGetOneFrame, this, [=](const QImage &img) {
//                        if (m_videoLabel1) m_videoLabel1->setPixmap(QPixmap::fromImage(img));
//                    });
//                    connect(m_ffmpeg1, &FFmpegKits::sigPlayError, this, [=](const QString &err) {
//                        qCritical() << "通道1主码流错误:" << err;
//                        QMessageBox::warning(this, "播放错误", QString("通道1主码流播放失败: %1").arg(err));
//                    });
//                }
//                // 3. 启动播放
//                m_ffmpeg1->startPlay(rtspUrl);
//                if (m_channel1Label) m_channel1Label->setText("通道1 (主码流)");
//            }
//            else {
//                // 切换到子码流
//                qDebug() << "切换到通道1子码流";

//                // 1. 停止主码流
//                if (m_ffmpeg1 && m_ffmpeg1->isPlaying()) {
//                    qDebug() << "停止通道1主码流播放器";
//                    m_ffmpeg1->stopPlay();
//                    // 等待线程完全停止
//                    QElapsedTimer timer;
//                    timer.start();
//                    while (m_ffmpeg1->isRunning() && timer.elapsed() < 5000) {
//                        QThread::msleep(10);
//                    }
//                    qDebug() << "通道1主码流播放器已停止";
//                }

//                // 2. 确保子码流播放器存在
//                if (!m_ffmpeg2) {
//                    m_ffmpeg2 = new FFmpegKits(this);
//                    connect(m_ffmpeg2, &FFmpegKits::sigGetOneFrame, this, [=](const QImage &img) {
//                        if (m_videoLabel1) m_videoLabel1->setPixmap(QPixmap::fromImage(img));
//                    });
//                    connect(m_ffmpeg2, &FFmpegKits::sigPlayError, this, [=](const QString &err) {
//                        qCritical() << "通道1子码流错误:" << err;
//                        QMessageBox::warning(this, "播放错误", QString("通道1子码流播放失败: %1").arg(err));
//                    });
//                }

//                // 3. 启动播放
//                m_ffmpeg2->startPlay(rtspUrl);
//                if (m_channel1Label) m_channel1Label->setText("通道1 (子码流)");
//            }
//            break;

//        case 2:
//            if (isMainStream) {
//                // 切换到主码流
//                qDebug() << "切换到通道2主码流";

//                // 1. 停止子码流
//                if (m_ffmpeg4 && m_ffmpeg4->isPlaying()) {
//                    qDebug() << "停止通道2子码流播放器";
//                    m_ffmpeg4->stopPlay();
//                    // 等待线程完全停止
//                    QElapsedTimer timer;
//                    timer.start();
//                    while (m_ffmpeg4->isRunning() && timer.elapsed() < 5000) {
//                        QThread::msleep(10);
//                    }
//                    qDebug() << "通道2子码流播放器已停止";
//                }

//                // 2. 确保主码流播放器存在
//                if (!m_ffmpeg3) {
//                    m_ffmpeg3 = new FFmpegKits(this);
//                    connect(m_ffmpeg3, &FFmpegKits::sigGetOneFrame, this, [=](const QImage &img) {
//                        if (m_videoLabel2) m_videoLabel2->setPixmap(QPixmap::fromImage(img));
//                    });
//                    connect(m_ffmpeg3, &FFmpegKits::sigPlayError, this, [=](const QString &err) {
//                        qCritical() << "通道2主码流错误:" << err;
//                        QMessageBox::warning(this, "播放错误", QString("通道2主码流播放失败: %1").arg(err));
//                    });
//                }

//                // 3. 启动播放
//                m_ffmpeg3->startPlay(rtspUrl);
//                if (m_channel2Label) m_channel2Label->setText("通道2 (主码流)");

//            } else {
//                // 切换到子码流
//                qDebug() << "切换到通道2子码流";

//                // 1. 停止主码流
//                if (m_ffmpeg3 && m_ffmpeg3->isPlaying()) {
//                    qDebug() << "停止通道2主码流播放器";
//                    m_ffmpeg3->stopPlay();
//                    // 等待线程完全停止
//                    QElapsedTimer timer;
//                    timer.start();
//                    while (m_ffmpeg3->isRunning() && timer.elapsed() < 5000) {
//                        QThread::msleep(10);
//                    }
//                    qDebug() << "通道2主码流播放器已停止";
//                }

//                // 2. 确保子码流播放器存在
//                if (!m_ffmpeg4) {
//                    m_ffmpeg4 = new FFmpegKits(this);
//                    connect(m_ffmpeg4, &FFmpegKits::sigGetOneFrame, this, [=](const QImage &img) {
//                        if (m_videoLabel2) m_videoLabel2->setPixmap(QPixmap::fromImage(img));
//                    });
//                    connect(m_ffmpeg4, &FFmpegKits::sigPlayError, this, [=](const QString &err) {
//                        qCritical() << "通道2子码流错误:" << err;
//                        QMessageBox::warning(this, "播放错误", QString("通道2子码流播放失败: %1").arg(err));
//                    });
//                }

//                // 3. 启动播放
//                m_ffmpeg4->startPlay(rtspUrl);
//                if (m_channel2Label) m_channel2Label->setText("通道2 (子码流)");
//            }
//            break;
//        }

//        qDebug() << "通道" << channel << (isMainStream ? "主码流" : "子码流") << "URL:" << rtspUrl;
//    } catch (const std::exception& e) {
//        qCritical() << "启动视频播放时发生异常:" << e.what();
//        QMessageBox::critical(this, "播放错误", QString("启动视频播放时发生异常: %1").arg(e.what()));
//    } catch (...) {
//        qCritical() << "启动视频播放时发生未知异常";
//        QMessageBox::critical(this, "播放错误", "启动视频播放时发生未知异常");
//    }
//}
//设置云台控制连接
void VideoMonitorWindow::setupPTZConnections()
{
    connect(m_btnUp,&QPushButton::clicked,this,[this](){handlePTZCommand("u");});
    connect(m_btnDown,&QPushButton::clicked,this,[this](){handlePTZCommand("d");});
    connect(m_btnLeft,&QPushButton::clicked,this,[this](){handlePTZCommand("l");});
    connect(m_btnRight,&QPushButton::clicked,this,[this](){handlePTZCommand("r");});
    connect(m_btnLon,&QPushButton::clicked,this,[this](){handlePTZCommand("1");});
    connect(m_btnRon,&QPushButton::clicked,this,[this](){handlePTZCommand("2");});
    connect(m_btnLup,&QPushButton::clicked,this,[this](){handlePTZCommand("3");});
    connect(m_btnRup,&QPushButton::clicked,this,[this](){handlePTZCommand("4");});
    // 连接变焦控制按钮
    connect(m_btnZoomIn, &QPushButton::clicked, this, [this]() { handlePTZCommand("f"); }); // 变焦+
    connect(m_btnZoomOut, &QPushButton::clicked, this, [this]() { handlePTZCommand("n"); }); // 变焦-

    // 连接聚焦控制按钮
    connect(m_btnFocusIn, &QPushButton::clicked, this, [this]() { handlePTZCommand("i"); }); // 聚焦+
    connect(m_btnFocusOut, &QPushButton::clicked, this, [this]() { handlePTZCommand("o"); }); // 聚焦-

    // 连接中心按钮（停止）
    connect(m_btnCenter, &QPushButton::clicked, this, [this]() { handlePTZCommand("s"); }); // 停止

    // 初始化网络管理器
    if (!m_networkManager) {
        m_networkManager = new QNetworkAccessManager(this);
    }
}
void VideoMonitorWindow::setPTZDuration(int duration)
{
    m_ptzDuration = duration;

    // 更新PTZ持续时间标签（如果存在）
    if (m_ptzDurationLabel) {
        m_ptzDurationLabel->setText(QString("%1ms").arg(duration));
    }

    // 更新PTZ定时器的间隔
    if (m_ptzTimer) {
        m_ptzTimer->setInterval(duration);
    }

    addLogMessage(QString("设置云台点动时间为: %1 毫秒").arg(duration));
}
// 实现handlePTZCommand函数
void VideoMonitorWindow::handlePTZCommand(const QString &command)
{
    // 只有通道1有云台控制功能
    if (m_currentChannel != 1) {
        QMessageBox::information(this, "提示", "只有通道1支持云台控制");
        return;
    }

    // 根据命令代码获取描述
    QString description;
    if (command == "u") description = "按下按键向上";
    else if (command == "d") description = "按下按键向下";
    else if (command == "l") description = "按下按键向左";
    else if (command == "r") description = "按下按键向右";
    else if (command == "1") description = "按下按键向左上";
    else if (command == "2") description = "按下按键向右上";
    else if (command == "3") description = "按下按键向左下";
    else if (command == "4") description = "按下按键向右下";
    else if (command == "n") description = "按下按键变焦-";
    else if (command == "f") description = "按下按键变焦+";
    else if (command == "i") description = "按下按键聚焦+";
    else if (command == "o") description = "按下按键聚焦-";
    else if (command == "s") description = "按下按键停止";

    // 添加日志
    addLogMessage(QString("已执行: %1 (%2)").arg(description).arg(command));

    // 通过TCP客户端发送云台控制命令到服务器
    m_tcpClient->sendPTZControlRequest(1, command, m_ptzDuration);

    // 启动定时器，0.5秒后停止运动（除了停止命令本身）
    if (command != "s") {
        m_ptzTimer->start(m_ptzDuration); // 500毫秒 = 0.5秒
    }
}
// 处理云台控制结果
void VideoMonitorWindow::onPTZControlResult(bool success, const QString &msg) {
    //    if (success) {
    //        addLogMessage("云台控制命令执行成功");
    //    } else {
    //        addLogMessage(QString("云台控制命令执行失败: %1").arg(msg));
    //        QMessageBox::warning(this, "云台控制失败", msg);
    //    }
    //    qDebug() << "云台控制结果 - 成功:" << success << "消息:" << msg;
    if (success) {
        addLogMessage("云台控制命令执行成功");
    } else {
        addLogMessage(QString("云台控制命令执行失败: %1").arg(msg));
        // 只在非"无效的响应格式"错误时显示弹窗
        if (msg != "无效的响应格式") {
            QMessageBox::warning(this, "云台控制失败", msg);
        }
    }
    qDebug() << "云台控制结果 - 成功:" << success << "消息:" << msg;
}
void VideoMonitorWindow::stopPTZMovement()
{
    m_tcpClient->sendPTZControlRequest(1,"s",0);
}
//void VideoMonitorWindow::sendPTZCommand(const QString &command)
//{
//    qDebug() << "发送云台控制指令:" << command;

//    // 构建API URL
//    //QUrl url(QString("http://%1/xsw/api/ptz/control").arg(m_cameraIp1));

//    // 根据命令设置value参数
//    QString value;
//    if (command == "u") value = "up";
//    else if (command == "d") value = "down";
//    else if (command == "l") value = "left";
//    else if (command == "r") value = "right";
//    else if (command == "1") value = "leftup";    // 左上
//    else if (command == "2") value = "rightup";   // 右上
//    else if (command == "3") value = "leftdown";  // 左下
//    else if (command == "4") value = "rightdown"; // 右下
//    else if (command == "n") value = "zoomin";    // 变焦-
//    else if (command == "f") value = "zoomout";   // 变焦+
//    else if (command == "i") value = "focusin";   // 聚焦+
//    else if (command == "o") value = "focusout";  // 聚焦-
//    else if (command == "s") value = "stop";      // 停止

//    // 使用KVQuery构建参数
//    KVQuery params;
//    params.add("value", value.toStdString());
//    params.add("speed", "5");
//    params.add("steps", "10");
//    if (command == "s") {
//        params.add("stop", "1");
//    }

//    // 生成加密后的参数字符串（包含token）
//    string queryStr = params.toCrpytString();
//    url.setQuery(QString::fromStdString(queryStr));

//    // 创建GET请求
//    //QNetworkRequest request(url);
//    // 设置认证信息
//    QString auth = QString("%1:%2").arg("admin").arg("admin");
//    request.setRawHeader("Authorization", "Basic " + auth.toUtf8().toBase64());

//    // 发送GET请求（替换原来的POST）
//    QNetworkReply *reply = m_networkManager->get(request);
//    connect(reply, &QNetworkReply::finished, this, [this, reply, command]() {
//        if (reply->error() != QNetworkReply::NoError) {
//            addLogMessage(QString("命令 %1 发送失败: %2").arg(command).arg(reply->errorString()));
//            qDebug() << "云台控制错误:" << reply->errorString();
//            qDebug() << "响应内容:" << reply->readAll();
//        } else {
//            // 解析JSON响应
//            QByteArray responseData = reply->readAll();
//            QJsonDocument doc = QJsonDocument::fromJson(responseData);
//            if (!doc.isNull() && doc.isObject()) {
//                QJsonObject json = doc.object();
//                int code = json["code"].toInt();
//                QString msg = json["msg"].toString();

//                if (code == 0) {
//                    addLogMessage(QString("命令 %1 发送成功: %2").arg(command).arg(msg));
//                } else {
//                    addLogMessage(QString("命令 %1 执行失败: %2").arg(command).arg(msg));
//                }
//            } else {
//                addLogMessage(QString("命令 %1 响应解析失败").arg(command));
//            }
//        }
//        reply->deleteLater();
//    });
//}
//添加日志信息
void VideoMonitorWindow::addLogMessage(const QString &message)
{
    QString currentTime=QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
    // 添加带时间戳的日志消息
    m_logTextEdit->append(QString("[%1] %2").arg(currentTime).arg(message));

    // 自动滚动到底部
    QTextCursor cursor = m_logTextEdit->textCursor();
    cursor.movePosition(QTextCursor::End);
    m_logTextEdit->setTextCursor(cursor);
}
// ==================== 鼠标事件重写（保留原功能） ====================
void VideoMonitorWindow::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton) {
        m_dragPosition = event->globalPos() - frameGeometry().topLeft();
        event->accept();
    }
    QMainWindow::mousePressEvent(event);
}

void VideoMonitorWindow::mouseMoveEvent(QMouseEvent *event)
{
    if (event->buttons() & Qt::LeftButton) {
        move(event->globalPos() - m_dragPosition);
        event->accept();
    }
    QMainWindow::mouseMoveEvent(event);
}

void VideoMonitorWindow::mouseDoubleClickEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton) {
        isMaximized() ? showNormal() : showMaximized();
        event->accept();
    }
    QMainWindow::mouseDoubleClickEvent(event);
}
